package com.chengang.crawler.jd.util;

import com.chengang.crawler.jd.config.GirlProperties;
import com.chengang.crawler.jd.config.HttpClientProperties;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

/**
 * @author 陈刚
 * @ClassName HttpUtils
 * @Description //TODO
 * @create 2020-02-08 22:10
 */
@Component
public class HttpUtils {

    private PoolingHttpClientConnectionManager cm;

    private static Integer maxTotal;

    private static Integer defaultMaxPerRoute;

    public static Integer getMaxTotal() {
        return maxTotal;
    }

    @Value("${httpClient.maxTotal}")
    public static void setMaxTotal(Integer maxTotal) {
        HttpUtils.maxTotal = maxTotal;
    }

    @Value("${httpClient.defaultMaxPerRoute}")
    public static Integer getDefaultMaxPerRoute() {
        return defaultMaxPerRoute;
    }

    public static void setDefaultMaxPerRoute(Integer defaultMaxPerRoute) {
        HttpUtils.defaultMaxPerRoute = defaultMaxPerRoute;
    }

    public PoolingHttpClientConnectionManager getCm() {
        return cm;
    }

    public void setCm(PoolingHttpClientConnectionManager cm) {
        this.cm = cm;
    }

    @Autowired
    GirlProperties hc;
    private static String prefix;
    static {
        prefix = ClassLoader.getSystemResource("").toString().replace("target/classes/","").replace("file:/","");
        System.out.println(prefix);
    }
    private HttpUtils() {
        this.cm = new PoolingHttpClientConnectionManager();

        this.cm.setMaxTotal(1000);
        this.cm.setDefaultMaxPerRoute(10);
    }

    /**
     * 根据请求地址下载页面
     * @param url
     * @return
     */
    public String doGetHtml(String url) {
        //获取httpclient对象
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(this.cm).build();
        //创建httpclient请求对象，设置url地址
        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(this.getConfig());
        httpGet.setHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0");
        //使用HttpClient发起请求，获取响应
        CloseableHttpResponse response = null;
        try {
           response = httpClient.execute(httpGet);

            //解析响应
            if (response.getStatusLine().getStatusCode() == 200) {
                if (response.getEntity() != null) {
                    String content = EntityUtils.toString(response.getEntity(), "utf8");
                    return content;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
        return StringUtils.EMPTY;
    }

    @Value("${requestConfig.connectTimeout}")
    private Integer connectTime;

    @Value("${requestConfig.connectionRequestTimeout}")
    private Integer connectionRequestTimeout;

    @Value("${requestConfig.socketTimeout}")
    private Integer socketTimeout;

    //设置请求信息
    private RequestConfig getConfig() {
        return RequestConfig.custom().setConnectTimeout(connectTime)//创建链接的最长时间
                .setConnectionRequestTimeout(connectionRequestTimeout)//获取链接的最长时间
                .setSocketTimeout(socketTimeout)//数据传输的最长时间
                .build();
    }

    /**
     * 根据请求地址下载图片
     * @param url
     * @return 图片名称
     */
    public String doGetImage(String url) {

        //获取httpclient对象
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(this.cm).build();
        //创建httpclient请求对象，设置url地址
        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(this.getConfig());
        //使用HttpClient发起请求，获取响应
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);

            //解析响应
            if (response.getStatusLine().getStatusCode() == 200) {
                if (response.getEntity() != null) {
                    //下载图片

                    //获取图片后缀
                    String suffix = url.substring(url.lastIndexOf("."));

                    //重命名
                    String picName = UUID.randomUUID().toString()+suffix;

                    //下载图片
                    System.out.println(picName);

                    OutputStream stream = new FileOutputStream(new File(prefix+"images/"+picName));
                    response.getEntity().writeTo(stream);
                    return picName;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
        return StringUtils.EMPTY;
    }
}
